<template>
  <div class="dataAnalysisBody">
    <x-header v-if="!this.$fromApp(this)" :left-options="{backText: ''}">数据分析
    </x-header>
    <div class="searchGroup display-flex flex-direction-row align-items-center justify-content-flex-center">
      <div class="dateBox">
        <datetime class="selectDate display-flex flex-direction-row align-items-center justify-content-flex-center" v-model="startDate" @on-change="change"></datetime>
      </div>
      <p>至</p>
      <div class="dateBox">
        <datetime class="selectDate display-flex flex-direction-row align-items-center justify-content-flex-center" v-model="endDate" :start-date="startDate" @on-change="change"></datetime>
      </div>
      <p class="searchBtn display-flex flex-direction-row align-items-center justify-content-flex-center" @click="comfirm"><span>确定</span></p>
    </div>
    <button-tab class="btnGroup" v-model="btnState">
      <button-tab-item @on-item-click="choseQuickDate(0)">今日</button-tab-item>
      <button-tab-item @on-item-click="choseQuickDate(1)">近7天</button-tab-item>
      <button-tab-item @on-item-click="choseQuickDate(2)">本月</button-tab-item>
    </button-tab>
    <div class="chartBox">
      <p class="chartTitle">商品分类销售额占比</p>
      <v-chart
        ref="demo"
        :width="220"
        :data="data"
        :padding="[0, 'auto']">
        <v-tooltip disabled />
        <v-scale y :options="yOptions" />
        <v-pie :radius="0.75" :inner-radius="0.65" series-field="name" :colors="legendColorArr" />
        <v-legend :options="legendOptions" disabled/>
        <v-guide type="html" :options="htmlOptions" />
      </v-chart>
      <div class="chartBottom display-flex flex-direction-row justify-content-flex-justify">
        <div>
          <p>订单金额： <span>{{dataArr.totalSaleOrderAmount?dataArr.totalSaleOrderAmount:0}}</span></p>
          <p>优惠金额： <span>{{dataArr.totalDiscountAmount?dataArr.totalDiscountAmount:0}}</span></p>
          <p>订单数： <span>{{dataArr.totalSaleOrderCount?dataArr.totalSaleOrderCount:0}}</span></p>
          <p>客单价： <span>{{dataArr.avgSaleOrderAmount?dataArr.avgSaleOrderAmount:0}}</span></p>
          <!--<p>实收金额： <span>{{dataArr.totalRealAmount?dataArr.totalRealAmount:0}}</span></p>-->
        </div>
        <div>
          <p>新增客户数： <span>{{dataArr.newCustomerNum?dataArr.newCustomerNum:0}}</span></p>
          <p>下单客户数： <span>{{dataArr.orderCustomerNum?dataArr.orderCustomerNum:0}}</span></p>
          <p>未下单客户数： <span>{{dataArr.unOrderCustomerNum?dataArr.unOrderCustomerNum:0}}</span></p>
        </div>

      </div>
      <ul>
        <li v-for="(item, index) in data" :key="index"  class="display-flex flex-direction-row align-items-center" >
          <i class="legendColor" :style="{backgroundColor:item.color}"></i>
          <span class="legendName" style="color: #666666">{{item.name}}</span>&nbsp;&nbsp;
          <span style="color: #222222" v-if="-1 != item.type">{{item.percent}}%</span>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
  import { Datetime, VChart, VLine, VArea, VTooltip, VLegend, VBar, VPie, VGuide, VScale, ButtonTab, ButtonTabItem } from 'vux'

  let data = [
    // { name: '股票类', percent: 83.59, a: '1' },
    // { name: '债券类', percent: 2.17, a: '1' },
    // { name: '现金类', percent: 14.24, a: '1' }
  ]

  let map = {}
  data.map(obj => {
    map[obj.name] = obj.percent + '%'
  })


  export default {
    name: "DataAnalysis",
    components:{
      Datetime,
      VChart,
      VLine,
      VArea,
      VTooltip,
      VLegend,
      VBar,
      VPie,
      VGuide,
      VScale,
      ButtonTab,
      ButtonTabItem
    },
    data(){
      return{
        startDate:'',
        endDate:'',
        befoerWeekDate:'',
        btnState:2,
        legendColorArr:['#EEEEEE','#4BC1A1','#FF6C62','#57C8F2','#A0D468','#FFCE54','#CCD1D9','#CCD1D9','#527DD9','#254075','#7898BB','#FDB376','#FE3B49'],
        dataArr:{
          categoryList:[
            {categoryId:1,categoryName:'鸡',percentage:10,totalOrderAmount:0,totalOrderCount:0}
          ],
          totalSaleOrderAmount:0,
          totalSaleOrderCount:0
        },
        map,
        htmlOptions: {
          position: [ '50%', '50%' ],
          html: `
          <div style="width: 250px;height: 40px;text-align: center;">
            <div style="font-size: 16px;color: #666666">销售额</div>
            <div style="font-size: 16px;color: #666666">占比</div>
          </div>`
        },
        legendOptions: {
          position: 'right',
          showTitle:false,
          titleStyle:{
            fontSize:12,
            fill:'#000000'
          },
          itemFormatter (val) {
            return val + '  ' + map[val]
          }
        },
        yOptions: {
          formatter (val) {
            return val * 100 + '%'
          }
        },
        data:data
      }
    },
    created(){
      this.getNowDate();
    },
    mounted(){
      this.getInitData();
      // console.log(this.$refs.demo)
    },
    methods:{
      getInitData(){
        if(this.startDate!=''){
          var d1 = new Date(this.startDate);
          var d2 = new Date(d1);
          d2.setFullYear(d2.getFullYear()+1);
          d2.setDate(d2.getDate()-1);
          // console.log(d2.getTime());
          // console.log(new Date(this.endDate).getTime())
          if(new Date(this.endDate).getTime()>d2.getTime()){
            this.$vux.toast.text('单次只能查1年内的数据!', 'center');
            return;
          }
        }

        let params = {
          startTime:this.startDate,
          endTime:this.endDate + ' 23:59:59'
        }
        this.getData(params);
      },
      getData(params){
        this.$ajax.get('report/analysis',(res)=>{
          console.log(res);
          if(res.code == '200'){
            this.dataArr = res.data;
            if(this.dataArr){
              if(this.dataArr.categoryList){
                for(let i=0;i<this.dataArr.categoryList.length;i++){
                  this.dataArr.categoryList[i].name = this.dataArr.categoryList[i].categoryName?this.dataArr.categoryList[i].categoryName:'';
                  this.dataArr.categoryList[i].percent = this.dataArr.categoryList[i].percentage;
                  this.dataArr.categoryList[i].color = this.legendColorArr[i];
                }
              }else{
                this.dataArr=res.data;
                this.dataArr.categoryList=[];
                let obj={name:"暂无销售数据！",percent:100,type:-1,color:'#EEEEEE'};
                this.dataArr.categoryList.push(obj);
              }
            }else{
              this.dataArr={};
              this.dataArr.categoryList=[];
              let obj={name:"暂无销售数据！",percent:100,type:-1,color:'#EEEEEE'};
              this.dataArr.categoryList.push(obj);
            }
            this.data = JSON.parse(JSON.stringify(this.dataArr.categoryList));
            //console.log('=s=s=s',this.data)
            this.$nextTick(()=>{
              this.$refs.demo.rerender();
            })
          }
        },params)
      },
      comfirm(){
        this.btnState = 99;
        this.getInitData();

        this.data = [];
        map = {};
        if(this.dataArr&&this.dataArr.categoryList){
          let newData = this.dataArr.categoryList;
          for (let i=0;i<newData.length;i++){
            this.$set(this.data, i,  newData[i])
          }
          data.map(obj => {
            map[obj.name] = obj.percent + '%'
          })
        }
        this.$refs.demo.rerender();

      },
      change (value) {
        // console.log('change', value)
        // console.log('change1', this.startDate)
        // console.log('change2', this.endDate)
        if(this.startDate>this.endDate){
          this.endDate = this.startDate;
        }
      },
      choseQuickDate(val){
        this.getNowDate();
        this.btnState = val;
        var param;
        if(val == 0){
          param = {
            startTime:this.endDate,
            endTime:this.endDate + ' 23:59:59'
          };
        }else if(val == 1){
          param = {
            startTime:this.befoerWeekDate,
            endTime:this.endDate + ' 23:59:59'
          }
          //this.$vux.toast.text(param, 'center');
        }else if(val == 2){
          param = {
            startTime:this.startDate,
            endTime:this.endDate + ' 23:59:59'
          }
        }
        this.getData(param);
      },
      getNowDate(){
        var date = new Date();
        var seperator1 = "-";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
          month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
          strDate = "0" + strDate;
        }
        var monthFirstDay =  year + seperator1 + month + seperator1 + '01';
        var currentdate = year + seperator1 + month + seperator1 + strDate;
        this.startDate = monthFirstDay + '';
        this.endDate = currentdate+'';
        // this.endDate.replace(/\-/g,"/") 这里转换是因为在苹果浏览器里面 只能识别 XXXX/XX/XX
        var de = this.endDate.replace(/\-/g,"/") + ' 00:00:00';

        this.befoerWeekDate = this.timestampToTime(new Date(de).getTime()-604800000);

      },
      timestampToTime(timestamp) {
        //var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var Y = date.getFullYear() + '-';
        var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
        var D = (date.getDate() < 10 ? '0'+date.getDate() : date.getDate()) + ' ';
        var h = (date.getHours() < 10 ? '0'+date.getHours() : date.getHours()) + ':';
        var m = (date.getMinutes() < 10 ? '0'+date.getMinutes() : date.getMinutes()) + ':';
        var s = (date.getSeconds() < 10 ? '0'+date.getSeconds() : date.getSeconds());
        return Y+M+D+h+m+s;
      }
    }
  }
</script>

<style lang="less" type="text/less" scoped>
  ul>li{
    list-style: none;
  }
  .dataAnalysisBody{
    background-color: #ffffff;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    .searchGroup{
      margin: 0.4rem 0.3rem;
      p{
        margin: 0 .17rem;
      }
      .dateBox{
        /*border-radius: 8px;*/
        width: 2.5rem;
        /*height: 0.56rem;*/
        /*padding-top: .1rem;*/
        /*background-color: #f5f5f5;*/
        /*text-align: center;*/
        /*text-indent: 5px;*/
        /*border: 1px solid #EBEBEB;*/
        .selectDate{
          width: 2.5rem;
          height: 0.56rem;
          line-height: 0.56rem;
          border: 1px solid #DDDDDD;
          border-radius: 4px;
          text-align: center;
          padding: 0;
        }
      }
      .searchBtn{
        width: 1.44rem;
        height: 0.56rem;
        text-align: center;
        color: #ffffff;
        background-color: #8E91A0;
        border-radius: 8px;
        margin-left: 0.18rem;
        font-size: 16px;
      }
    }
    .btnGroup{
      margin: 0 0.3rem;
    }
    .chartBox{
      position: relative;
      .chartTitle{
        width: 100%;
        text-align: center;
        color: #222222;
        font-size: 21px;
        /*font-weight: bold;*/
        margin-top: .3rem;
      }
      .chartBottom{
        margin: 0 .5rem;
        font-size: 14px;
        p{
          color: #999999;
          margin-bottom: 5px;
          span{
            color: #333333;
          }
        }
      }
      ul{
        position: absolute;
        top: 2.1rem;
        right: .4rem;
        .legendColor{
          width: .32rem;
          height: .08rem;
          border-radius: .04rem;
          margin-right: .08rem;
        }
        .legendName{
          width: 1.5rem;
          text-overflow: ellipsis;
          white-space: nowrap;
          overflow: hidden;
        }
      }
    }
  }
</style>
